import TIM from 'tim-wx-sdk';
import PRSN from "@/js_sdk/wa-permission/permission.js";
import area from "@/components/citySelect/city-data/area.js";
import city from "@/components/citySelect/city-data/city.js";
import province from "@/components/citySelect/city-data/province.js";
import API from "@/common/api.js";
import {
	genTestUserSig
} from '@/sdk/timWx/GenerateTestUserSig.js';
import Request from "@/sdk/pocky-request/index.js"; //引入
export default {
	/**
	 * @description 根据经纬度获取亮点之间的距离
	 * @param {Float} lat1 目标点经度
	 * @param {Float} lng1	目标点纬度
	 * @param {Float} lat2	当前定位经度
	 * @param {Float} lng2	当前定位纬度
	 */
	getDis(lat1,lng1,lat2,lng2){
		let EARTH_RADIUS = 6378137.0; //单位M
		let PI = Math.PI;
		
		function getRad(d) {
			return d * PI / 180.0;
		}
		
		var radLat1 = getRad(lat1);
		var radLat2 = getRad(lat2);
		
		var a = radLat1 - radLat2;
		var b = getRad(lng1) - getRad(lng2);
		
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
			Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000.0;
		
		if (s > 1000) {
			s = (s / 1000).toFixed(2) + 'km'
		} else {
			s = s.toFixed(2) + '米'
		}
		return s;
	},
	
	/**
	 * @description 字节数转换为 B，KB，MB等
	 * @param {Object} bytes
	 * @return {String}
	 */
	bytesToSize(bytes) {
		if (bytes === 0) return '0 B';
		let k = 1024,
			sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
			i = Math.floor(Math.log(bytes) / Math.log(k));
		return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
	},
	getTm(_time) {
		// console.log(_time);

		var theTime = parseInt(_time); // 秒
		var middle = 0; // 分
		var hour = 0; // 小时

		if (theTime > 60) {
			middle = parseInt(theTime / 60);
			theTime = parseInt(theTime % 60);
			if (middle > 60) {
				hour = parseInt(middle / 60);
				middle = parseInt(middle % 60);
			}
		}
		var result = "" + parseInt(theTime) + "秒";
		if (middle > 0) {
			result = "" + parseInt(middle) + "分钟" + result;
		}
		if (hour > 0) {
			result = "" + parseInt(hour) + "小时" + result;
		}
		return result;

	},
	isStart(_str){
		let _now=new Date().getTime();
		let _year=parseInt( _str.split(' ')[0].split('-')[0]);
		let _month=parseInt(_str.split(' ')[0].split('-')[1])-1;
		let _day=parseInt(_str.split(' ')[0].split('-')[2]);
		let _hour=parseInt(_str.split(' ')[1].split(':')[0]);
		let _min=parseInt(_str.split(' ')[1].split(':')[1]);
		let _sec=parseInt(_str.split(' ')[1].split(':')[2]);
		let _n=new Date();
		_n.setFullYear(_year,_month,_day)
		_n.setHours(_hour);
		_n.setMinutes(_min);
		_n.setSeconds(_sec);
		console.log(_n.toString());
		let _nTim=_n.getTime();
		return _now>_nTim;
	},
	/**
	 * @description 将对象转化为URL后的参数，注意只能转化单层对象
	 * @param {Object} params 
	 * @return {String} 转化后的字符串
	 * @example paramsURL({id:123,name:'张三'})   =>  id=123&name=张三
	 */
	paramsURL(params) {
		let newParams = params;
		let newURL = '';


		for (const [key, val] of Object.entries(newParams || {})) {
			newURL += `${key}=${val}&`;
		}

		return newURL.substring(0, newURL.length - 1);
	},
	/**
	 * @description  带参url转换为object
	 * @param {Object} str  URL
	 * @return {Object}
	 */
	pramsUrlToObj(str) {
		let obj = {
			url: ''
		};
		let opt = {};
		if (str.split("?") < 1) {
			obj = {
				url: str
			}
		} else {
			var arr = str.split("?");
			obj = {
				url: arr[0]
			}
			if (arr[1]) {
				var arr2 = arr[1].split("&");
				for (var i = 0; i < arr2.length; i++) {
					var res = arr2[i].split("=");
					opt[res[0]] = res[1];
				}
			}
		}
		obj.opt = opt;
		return obj;
	},
	innerUrlToObj(str){
		let obj = {
			url: ''
		};
		if (str.split("?") < 1) {
			obj = {
				url: str
			}
		} else {
			var arr = str.split("?");
			obj = {
				url: arr[0]
			}
			if (arr[1]) {
				var arr2 = arr[1].split("&");
				for (var i = 0; i < arr2.length; i++) {
					var res = arr2[i].split("=");
					obj[res[0]] = res[1];
				}
			}
		}
		return obj;
	},
	/**
	 * @description  字符串转对象
	 * @param {Object} str
	 */
	strToObj(str) {
		let opt = {};
		var arr2 = str.split("&");
		for (var i = 0; i < arr2.length; i++) {
			var res = arr2[i].split("=");
			opt[res[0]] = res[1];
		}
		return opt;
	},
	/**
	 * @description 通过页面名检查页面是否已经打开
	 * @param {Object} pageName
	 * @return {Number} 如果已经打开过,返回回退需要的back数
	 */
	checkPageOpendByName(pageName) {
		let lastOpenIndex = 0; //最后一次打开index
		let openCount = 0; //已打开的数量
		let pageArr = getCurrentPages(); //获取页面栈数组
		let firstOpendIndex = 0; //第一次打开index
		//遍历页面栈,获取最后一次打开同名的index和已打开同名页面的数量
		pageArr.forEach(function(v, i) {
			//数组中判断是否有此页面  注意这边用的是array.indexOf方法
			let opd = v.route.split('/').indexOf(pageName) > 0;
			if (opd) {
				lastOpenIndex = i;
				openCount++;
				if (firstOpendIndex == 0) {
					firstOpendIndex = i;
				}
			}
		});
		return {
			opendCount: openCount, //已打开页面数
			lastOpendIndex: lastOpenIndex, //最后一次打开index
			firstOpendIndex: firstOpendIndex, //第一次打开index
			backLastLength: pageArr.length - lastOpenIndex - 1,
			backFirstLength: pageArr.length - firstOpendIndex - 1,
			pageCount: pageArr.length
		}
	},
	/**
	 * @description 创建本地推送消息
	 * @param {Object} msg
	 * msg 字段
	 * title push消息标题
	 * content push消息内容
	 * payload push消息参数
	 */
	createLocalMsg(msg) {
		plus.push.createMessage(msg.content, this.paramsURL(msg.payload), {
			title: msg.title,
			delay: 0,
			sound: 'system'
		})
	},

	/**
	 * @description 权限检查,当前APP用到了位置,推送,摄像头,定位,相册读写
	 * @param {String} prsn	需要检查的权限字符串
	 * location	位置
	 * push	推送
	 * camera	摄像头
	 * photoLibrary	相册
	 * record	麦克风
	 * contact	通讯录
	 * calendar	日历
	 * memo	备忘录
	 * call 拨打电话
	 */
	chackAppSinglePRSN(prsnStr) {
		return new Promise((resolve) => {
			// #ifdef APP-PLUS
			let sys = uni.getSystemInfoSync().platform;
			if (prsnStr == "location") {
				if (sys == "ios") { //苹果手机
					resolve(PRSN.judgeIosPermission("location") ? 1 : 0)
				} else { //安卓手机

					PRSN.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION').then(res => {
						resolve(res);
					});

				}
			} else if (prsnStr == "push") {
				if (sye == 'ios') {
					resolve(PRSN.judgeIosPermission("push") ? 1 : 0)
				} else {
					var main = plus.android.runtimeMainActivity();
					var NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
					if (areNotificationsEnabled) {
						resolve(1)
					} else {
						resolve(0)
					}
				}
			} else if (prsnStr == "camera") {
				if (sys == "ios") {
					resolve(PRSN.judgeIosPermission("camera") ? 1 : 0)
				} else {
					PRSN.requestAndroidPermission('android.permission.CAMERA').then(res => {
						resolve(res);
					});
				}
			} else if (prsnStr == "photoLibrary") {

			} else if (prsnStr == "call") {
				if (sys == "ios") { //苹果手机
					resolve(1); //苹果手机默认有拨打电话权限
				} else { //安卓手机
					PRSN.requestAndroidPermission('android.permission.CALL_PHONE').then(res => {
						resolve(res);
					});
				}
			} else {

			}
			// #endif

			// #ifdef MP-WEIXIN

			// #endif

		})

	},
	/**
	 * @description 拨打电话,拨打前会检查权限
	 * @param {Object} tel
	 */
	callPhone(tel) {
		// #ifdef APP-PLUS
		this.chackAppSinglePRSN("call").then(res => {
			if (res == -1) {
				uni.showModal({
					title: '权限申请',
					content: '拨打电话权限已被禁止，请授权后重试',
					showCancel: false,
					cancelText: '',
					confirmText: '确定',
					success: rlt => {
						if (rlt.confirm) {
							PRSN.gotoAppPermissionSetting();
						}
					},
				});

			} else {
				uni.makePhoneCall({
					phoneNumber: tel
				});
			}
		})
		// #endif

		// #ifdef MP
		uni.makePhoneCall({
			phoneNumber: tel
		});
		// #endif
	},
	/**
	 * @description 通过经纬度坐标打开地图
	 * @param {Object} shopData 店铺经纬度坐标
	 */
	toMapBylng(shopData) {
		// #ifdef APP-PLUS
		this.chackAppSinglePRSN("location").then(res => {
			if (res == -1) {
				uni.showModal({
					title: '权限申请',
					content: '获取位置权限已被禁止，请授权后重试',
					showCancel: false,
					cancelText: '',
					confirmText: '确定',
					success: rlt => {
						if (rlt.confirm) {
							PRSN.gotoAppPermissionSetting();
						}
					},
				});
			} else {
				uni.openLocation({
					latitude: shopData.lati,
					longitude: shopData.longi,
					name: shopData.name,
					address: shopData.address,
					success: function() {
						console.log('success');
					}
				});
			}
		});
		// #endif

		// #ifdef MP
		uni.openLocation({
			latitude: shopData.lati,
			longitude: shopData.longi,
			name: shopData.name,
			address: shopData.address,
			success: function() {
				console.log('success');
			}
		});
		// #endif

		// #ifdef H5
		// #endif
	},
	/**
	 * @description 登录页面跳转操作
	 * @param {Object} _this
	 * @param {Object} _next
	 * @param {Object} _type
	 */
	backDetail(_this) {
		// getApp().globalData.TIM_SDK_READY
		if (getApp().globalData.BACK_GOOD) {
			let pages = []; //页面栈
			pages = getCurrentPages();
			pages.reverse();
			let backNum = 0;
			pages.some((x, i) => {
				if (x.route.indexOf('goodDetail') > -1) {
					backNum = i;
					return true;
				}
			})
			if (getApp().globalData.BACK_NEXT) {
				uni.$emit("loginNext", {
					type: getApp().globalData.NEXT_TYPE
				});
			}
			uni.navigateBack({
				delta: backNum
			})
		} else {
			_this.toPage("index");
		}
	},
	/**
	 * @description 通过areaid获取省市区
	 * @param {Object} _areaId
	 * 
	 */
	getSSQByAreaId(_areaId) {
		_areaId = _areaId.toString();
		let _ctIndex, _areaIndex, _shIndex;
		area.forEach((item, n) => {
			// console.log(item);
			item.forEach((i, m) => {
				// console.log(i);
				i.forEach((x, y) => {
					// console.log(x);
					if (x.value == _areaId) {
						// console.log(x);
						_ctIndex = m;
						_areaIndex = y;
						_shIndex = n;
					}
				})

			})
		})

		return [province[_shIndex].label, city[_shIndex][_ctIndex].label, area[_shIndex][_ctIndex][_areaIndex].label]
	},



	/**
	 * @description 更新APP
	 * @param {Object} res 接口传递过来的更新信息
	 */
	updateApp(updateJson) {
		let _this = this;
		let _cachName = '';
		let _downUrl = '';
		if (updateJson.type == 1) { //差量更新
			_cachName = 'wgt-' + updateJson.latest
			_downUrl = updateJson.update_url
		} else { //全量更新
			_cachName = 'pkg-' + updateJson.latest
			_downUrl = updateJson.down_url
		}
		if(uni.getSystemInfoSync().platform=='ios' && updateJson.type==2){		//ios强制更新跳转APPstore
			plus.runtime.openURL('https://apps.apple.com/cn/app/%E6%89%BE%E5%9F%B9%E8%AE%AD%E5%B9%B3%E5%8F%B0/id1505062519');
			return;
		}
		_this.getLocalUpdatePackageByVersion(_cachName).then(storageUrl => { //用接口获取的版本号检查storage缓存
			if (storageUrl) { //有storage缓存
				console.log("有storage缓存" + storageUrl);
				_this.checkSavedUpdatePackage(storageUrl).then(filePath => { //通过storage缓存中的文件路径查看该文件存不存在
					if (filePath) { //存在走安装流程
						console.log("开始安装");
						_this.installUpdatePackage(filePath, updateJson);
		
					} else { //不存在先下载  
						_this.downloadFile(_downUrl,updateJson).then(tempFilePath => { //下载文件
							_this.saveFile(_cachName, tempFilePath).then(savedFilePath => { //存储下载的临时文件
								_this.installUpdatePackage(savedFilePath, updateJson);
							})
						});
					}
				})
			} else { //没有
				_this.downloadFile(_downUrl,updateJson).then(tempFilePath => { //下载文件
					_this.saveFile(_cachName, tempFilePath).then(savedFilePath => { //存储下载的临时文件
						_this.installUpdatePackage(savedFilePath, updateJson);
					})
				});
			}
		})
	},

	/**
	 * 检查已下载的文件中是否有指定文件
	 * @param {String} filePath -文件路径
	 * @return {String} [filePath,undefined]  如果有匹配的文件则返回文件地址，否则返回undefined
	 */
	checkSavedUpdatePackage(filePath) {
		return new Promise((resolve, reject) => {
			uni.getSavedFileList({ //获取已下载的文件
				success: (res) => {
					resolve(res.fileList.find(function(file) { //遍历查询已下载的文件中有没有该文件,有则返回该文件地址，没有则返回undefined
						return file.filePath == filePath
					}))
				},
				fail: (err) => {
					reject(err);
				}
			})
		})


	},
	/**
	 * @description 安装更新包
	 * @param {Object} filePath
	 */
	installUpdatePackage(filePath, _json) {
		let _this = this;
		plus.runtime.install(filePath, {
			force: true
		}, function() { //安装成功
			uni.setStorageSync("localVersion", _json.latest)
			// _this.removeFile(filePath).then(function() { //安装成功后清除本地文件


			// });
			
			// uni.showToast({
			// 	title: '安装更新包成功，正在重启应用',
			// 	icon: 'none'
			// });
			setTimeout(() => {
				plus.runtime.restart();
			}, 1500)



		}, function(err) { //安装失败
			// console.log(err);
			// uni.showToast({
			// 	title: '本地安装包已损坏正在重新下载',
			// 	icon: 'none'
			// });
			let _cachName = '';
			let _downUrl = '';
			if (_json.type == 1) { //差量更新
				_cachName = 'wgt-' + _json.latest
				_downUrl = _json.update_url
			} else { //全量更新
				_cachName = 'pkg-' + _json.latest
				_downUrl = _json.down_url
			}
			_this.downloadFile(_downUrl,_json).then(tempFilePath => { //下载文件
				_this.saveFile(_cachName, tempFilePath).then(savedFilePath => { //存储下载的临时文件
					_this.installUpdatePackage(savedFilePath, _json);
				})
			});
		});
	},

	/**
	 * @description 下载文件
	 * @param {Object} fileUrl=[需要下载的文件url]
	 * @example  https://www.hawklu.com/testPage/ranking.apk
	 */
	downloadFile(fileUrl,_json) {
		let _this = this;
		return new Promise((resolve, reject) => {
			console.log(fileUrl);
			const downloadTask = uni.downloadFile({
				url: fileUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						console.log("文件下载成功，暂存地址:" + res.tempFilePath);
						resolve(res.tempFilePath);

					} else {
						uni.showModal({
							title: '更新失败',
							content: '安装包下载失败，请检查网络或重启应用试试',
							showCancel: false,
							cancelText: '',
							confirmText: '确定',
							success: res => {},
							fail: () => {},
							complete: () => {
								plus.runtime.quit();
							}
						});
						reject(res);
					}
				},
				fail: err => {
					uni.showModal({
						title: '更新失败',
						content: '安装包下载失败，请检查网络或重启应用试试',
						showCancel: false,
						cancelText: '',
						confirmText: '确定',
						success: res => {},
						fail: () => {},
						complete: () => {
							plus.runtime.quit();
						}
					});
				}
			});

			// 下载中处理
			downloadTask.onProgressUpdate((res) => {
				// uni.showLoading({
				// 	title: '正在下载中...'+res.progress+'%',
				// 	mask: false
				// });
				if(_json.type==2){
					uni.$emit("downing", res);
				}
				// console.log('下载进度' + res.progress);
				// console.log('已经下载的数据长度' + res.totalBytesWritten);
				// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
				// 测试条件，取消下载任务。

			});
		})

	},
	/**
	 * @description 存储下载的文件
	 * @param {Object} tempFile  下载后暂存的文件路径，暂存文件在APP重启后会消失
	 * @param {String} version 安装包的版本号 
	 */
	saveFile(version, tempFilePath) {
		return new Promise((resolve, reject) => {
			uni.saveFile({
				tempFilePath: tempFilePath,
				success: function(res) {
					uni.setStorage({
						key: version,
						data: res.savedFilePath,
						success() {
							console.log("存储文件成功，存储地址：" + res.savedFilePath);
							resolve(res.savedFilePath);
						}
					})
				},
				fail: (err) => {
					console.log("存储文件失败");
				}
			});
		})

	},

	/**
	 * @description 通过版本号检查storage
	 * @param {Object} version
	 */
	getLocalUpdatePackageByVersion(version) {
		return new Promise((resolve, reject) => {
			uni.getStorage({
				key: version,
				success: (storageRes) => {
					resolve(storageRes.data)
				},
				fail() {
					console.log("通过版本号没有获取到文件");
					resolve(false);
				}
			})
		})
	},
	/**
	 * @param {Object} filePath 文件的路径
	 */
	removeFile(filePath) {
		return new Promise((resolve, reject) => {
			uni.removeSavedFile({
				filePath: filePath,
				success: () => {
					resolve()
				},
				fail: (reject) => {
					reject()
				},
				complete: function(res) {
					console.log(res);
				}
			});
		})
	},
	/**
	 * 获取下载目录所有的文件总大小
	 */
	getDownloadListSize() {
		let downloadSize = 0;
		let _this = this;
		return new Promise(resolve => {
			uni.getSavedFileList({
				success: (res) => {
					downloadSize = res.fileList.reduce(function(x, y) {
						return Number(x) + Number(y.size)
					}, 0);
					resolve(_this.bytesToSize(downloadSize));
				},
				fail: () => {
					console.log("获取下载目录文件总大小失败");
				}
			})
		})
	},
	async clearDownLoadFile(_fileArr) {
		let _this = this;;
		uni.showLoading({
			title: '清除缓存中...',
			mask: false
		});

		if (_fileArr.length > 0) {
			for (let i = 0; i < _fileArr.length; i++) {
				await _this.removeFile(_fileArr[i].filePath)
			}
		}
		// uni.clearStorageSync();
		setTimeout(() => {
			uni.hideLoading()
		}, 1500)
		console.log("清理完毕");
	},
	/**
	 * 检查剪贴板
	 */
	checkClipboard() {
		setTimeout(() => {
			uni.getClipboardData({
				success: (res) => {
					if(res.data){
						let reg = new RegExp("(#.*?#)", 'g');
						let str = res.data.toString().match(reg);
						if(str==null || str.length==0){
							
						}else{
							console.log(str[0]);
							Request().request({
								url: '/group/getToken.do',
								method: 'post',
								data: {
									gtoken:str[0]
								}
							}).then(apiRes => {
								if (apiRes.data.code == 1) {
									uni.$emit("showKlBox",{
										type:apiRes.data.data.split(',')[1],
										id:apiRes.data.data.split(',')[0]
									})
								} 
							})
						}
					}
				}
			})
			
		}, 3000)
		
	}

}
